import cv2
import json
import os
import requests
from pathlib import Path
from requests_toolbelt.multipart.encoder import MultipartEncoder
from datetime import datetime
import tqdm


class QuickEventProcessor:
    def __init__(self, fps=25, frame_size=(1280, 720), progress_callback=None):
        """
        :param fps: 视频帧率（默认25）
        :param frame_size: 视频分辨率（默认1280x720）
        """
        self.fps = fps
        self.frame_size = frame_size
        self.progress_callback = progress_callback

    def generate_video(self, image_dir: str, output_path: str):
        """
        生成快放视频（带进度显示）
        """
        # 建立输出目录
        output = Path(output_path)
        output.parent.mkdir(parents=True, exist_ok=True)

        # 获取排序后的图片
        images = sorted(
            Path(image_dir).glob("*.*"),
            key=lambda x: self._extract_number(x.stem)
        )
        total_frames = len(images)
        
        # 初始化视频编码器
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        video_writer = cv2.VideoWriter(output_path, fourcc, self.fps, self.frame_size)

        # 初始化进度条
        pbar = tqdm.tqdm(
            total=total_frames,
            desc="生成视频进度",
            unit="帧",
            bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]"
        )

        try:
            for idx, img_path in enumerate(images, 1):
                img = cv2.imread(str(img_path))
                if img is not None:
                    resized = cv2.resize(img, self.frame_size)
                    video_writer.write(resized)
                
                # 更新进度
                pbar.update(1)
                if self.progress_callback:
                    self.progress_callback(idx, total_frames)
                
                # 实时显示处理信息
                pbar.set_postfix({
                    "当前文件": img_path.name,
                    "分辨率": f"{self.frame_size[0]}x{self.frame_size[1]}",
                    "帧率": f"{self.fps}fps"
                })
                
        finally:
            video_writer.release()
            pbar.close()

    def _extract_number(self, filename: str) -> int:
        """从文件名提取排序数字"""
        return int(''.join(filter(str.isdigit, filename)))

    def upload_quick_info(
        self,
        video_path: str,
        api_url: str,
        camera_name: str,
        video_name: str,
        event_info: dict,
        remarks: str
    ):
        """
        上传快速事件信息
        :param video_path: 视频文件路径
        :param api_url: 接口地址
        :param camera_name: 摄像头名称
        :param video_name: 视频名称
        :param event_info: 快放事件信息字典（示例：{5: 2657}）
        :param remarks: 快放备注
        """
        video_file = Path(video_path)
        if not video_file.exists():
            raise FileNotFoundError(f"视频文件不存在: {video_path}")

        fields = {
            "cameraName": camera_name,
            "Name": video_name,
            "quickRemarks": remarks,
            "file": (video_file.name, open(video_file, 'rb'), 'video/mp4')
        }

        try:
            encoder = MultipartEncoder(fields=fields)
            response = requests.post(
                api_url,
                data=encoder,
                headers={'Content-Type': encoder.content_type},
                timeout=30
            )
            return response
        finally:
            fields['file'][1].close()  # 确保关闭视频文件

# 使用示例
if __name__ == "__main__":
    def print_progress(current, total):
        percent = current / total * 100
        print(f"\r自定义进度: {current}/{total} ({percent:.1f}%)", end="")

    processor = QuickEventProcessor(fps=25, frame_size=(960, 540),progress_callback=print_progress )


    # 生成视频
    image_folder = "/home/linaro/cw/yolo11"
    output_video = "/data/quick_events.mp4"
    # processor.generate_video(image_folder, output_video)

    # 上传数据
    response = processor.upload_quick_info(
        api_url="http://192.168.0.142:80/aiApi/saveQuickInfo",
        camera_name="chunk_0000",
        video_name="chunk_0000",
        remarks="本次视频时长1小时,发现2次机动车违章行为,违章率0.5%"
    )

    print(f"上传结果: {response.status_code}")
    print(f"响应内容: {response.text}")